const { connection } = require('../connect/connect')
var url = require('url');
var util = require('util');
const multer = require("multer");
var formidable = require('formidable');
const path=require("path");
const fs = require("fs");

// var form = new formidable.IncomingForm();
// form.uploadDir="./tmp";//设置文件上传的目录 目录需手动创建
// form.encoding = 'utf-8';//设置表单域的编码
// form.keepExtensions = true;//设置该属性为true可以使得上传的文件保持原来的文件的扩展名

exports.addAdvice = function(req, res){
    let form = new formidable.IncomingForm();
    form.encoding = 'utf-8';//设置表单域的编码
    form.uploadDir = path.join(__dirname + "/tmp");//设置上传文件存放的文件夹，默认为系统的临时文件夹，可以使用fs.rename()来改变上传文件的存放位置和文件名
    form.keepExtensions = true;//设置该属性为true可以使得上传的文件保持原来的文件的扩展名
    var sends = [];
    var JerryImg ='';
    form.parse(req, function (err, fields, fils){
        let key = Object.keys(fils);
        let check = 1;
        for(let j = 0;j<key.length;j++){
            let keyname = key[j]
            let filename = fils[keyname].name;
            let nameArray = filename.split('.')
            let type = nameArray[nameArray.length - 1];
            let name = '';
            for (let i = 0; i < nameArray.length - 1; i++) {
                name = name + nameArray[i];
            }
            if(name === ''){
                check = 0;
            }
            let date = new Date();
            let time = '_' + date.getFullYear() + "_" + date.getMonth() + "_" + date.getDay() + "_" + date.getHours() + "_" + date.getMinutes();
            let avatarName = name + time + '.' + type;
            let newPath = form.uploadDir + "/" + avatarName;
            fs.renameSync(fils[keyname].path, newPath);  //重命名
            sends.push(path.join(__dirname+'/tmp/'+avatarName));
            if(check !== 0){
                JerryImg = path.join(__dirname+'/tmp/'+avatarName);
            }
        }
        // res.send(sends[0])//返回的信息
        let params = url.parse(req.url,true).query
        let MyData = params.MyData;
        let usernameId = params.usernameId;
        let cate = params.cate;
        // console.log(JerryImg)
        let username = params.username;
        let sql = 'insert into advice(user_id,user_name,text,cate,book_img) values(?,?,?,?,?)'
        let paramsData = [usernameId,username,MyData,cate,JerryImg];
        connection.query(sql,paramsData,function(err,result){
            if(err){
                console.log(err)
                res.send(err);
            }else{
                res.send(result);
            }
        })
    })

}

exports.AdviceBook = function(req,res){
    let params = '书籍'
    let sql = "select * from advice where cate="+"'"+params+"'";
    connection.query(sql,function(err,result){
        if(err){
            res.send(err)
        }else{
            res.send(result)
        }
    })
}
